package com.sensePlusVR.setting.bluetooth;

import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.os.Build;

import com.cavan.android.CavanAndroid;
import com.jwaoo.android.JwaooBleToy;
import com.jwaoo.android.JwaooBleToy.JwaooBleToyEventListener;
import com.jwaoo.android.JwaooBleToy.JwaooToyBatteryInfo;
import com.jwaoo.android.JwaooBleToy.JwaooToyMotoMode;
import com.jwaoo.android.JwaooToySensor;
import com.sensePlusVR.application.VRApplication;
import com.sensePlusVR.utils.Constant;
import com.sensePlusVR.utils.MyLog;

@SuppressWarnings("static-access")
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class BluetoothPlayer {

	private static final String TAG = BluetoothPlayer.class.getSimpleName();
	private static final int SENSOR_DELAY = 20;
	private JwaooBleToy mBleToy;

	private BluetoothManager mBluetoothManager;
	private BluetoothAdapter mBluetoothAdapter;

	private Context mContext;
	private BluetoothDevice mDevice;

	// 蓝牙连接状态事件
	private BTEvent onBTEvent;

	// 蓝牙数据
	private BTDataMsg onBTDataMsg;

	// 是否上报数据
	private boolean isEventEnable = false;

	private static final float NoFilterSpeed = 0.45f;

	private static final float FilterSpeed = 0.7f;

	private BTDataProcess btDataProc;
	private BTBandDataProcess mBandDataProc;
	private BTDataState onBTState;

	private float smoothSpeed = NoFilterSpeed;

	private int btLevel = 0;

	private boolean isFilter = false;

	private double btData1;

	private double btData2;

	public BluetoothPlayer(Context context) {
		this.mContext = context;

		mBleToy =  JwaooBleToy.getInstance(mContext);

		mBleToy.setEventListener(jwaooBleToyEventListener);

	}

	// 连接蓝牙
	public void connect(String macAddr) {

		CavanAndroid.DLOG_ENABLE = true;
		CavanAndroid.ELOG_ENABLE = true;
		CavanAndroid.WLOG_ENABLE = true;
		CavanAndroid.PLOG_ENABLE = true;

		if (mBleToy != null) {

			mBleToy.disconnect();

		}

		mBluetoothManager = (BluetoothManager) mContext
				.getSystemService(mContext.BLUETOOTH_SERVICE);
		mBluetoothAdapter = mBluetoothManager.getAdapter();

		if (macAddr != "") {
			mDevice = mBluetoothAdapter.getRemoteDevice(macAddr);
		}
		if (mDevice == null) {
			MyLog.d(TAG, "mDevice == null...");
			return;
		} else {
			MyLog.d(TAG, "mDevice address : " + mDevice.getAddress());

			mBleToy.connect(mDevice);
		}

	}

	// 是否上报数据
	public synchronized void setSensorEnable(boolean enable) {

		isEventEnable = enable;

		onBTDataMsg = null;

		if (mBleToy != null) {
			try {
				mBleToy.setSensorEnable(isEventEnable, SENSOR_DELAY);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
	/**
	 * 判断是否支持切换FOV的按键，飞机杯支持，手环不支持
	 * 
	 * @return isSupported
	 */
	public synchronized boolean isSupportFovKey(){
		if (mBleToy.getDeviveId() == JwaooBleToy.DEVICE_ID_MODEL10)
			return false;
		return true;
	}
	/**
	 * 启动蓝牙设置回调
	 * 
	 * @param enable
	 * @param onBTDataMsg
	 */
	public synchronized void setSensorEnable(boolean enable,
			BTDataMsg onBTDataMsg) {

		isEventEnable = enable;

		this.onBTDataMsg = onBTDataMsg;

		if (mBleToy != null) {

			try {
				mBleToy.setSensorEnable(isEventEnable, SENSOR_DELAY);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	/**
	 * 是否连接上
	 * 
	 * @return
	 */
	public boolean isBTConnected() {

		if (mBleToy != null) {

			return mBleToy.isConnected();
		}

		return false;

	}


	/**
	 * 断开连接
	 */
	public void toBTDisconnect() {
		if (mBleToy != null) {
			mBleToy.disconnect();

		}
	}
	
	/**
	 * 注册的蓝牙监听广播
	 */
	public void registerBT(){
		
		if (mBleToy != null) {
			mBleToy.registerBroadcastReceiver();
		}
		
	}
	
	/**
	 * 取消蓝牙监听广播
	 */
	public void unregisterBT(){
		if(mBleToy != null){
			mBleToy.unregisterBroadcastReceiver();
		}
	}

	/**
	 * 获取电池信息
	 * 
	 * @return
	 */
	public JwaooToyBatteryInfo getBatteryInfo(String macAddr) {
		if (mBleToy != null) {
			JwaooToyBatteryInfo info;
			try {
				info = mBleToy.getBatteryInfo();
				MyLog.d(TAG, "info :" + info);
				return info;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		}
		return null;
	}

	public interface BTEvent {
		public void onConnected(boolean isConnected);
	}

	public void setBTEvent(BTEvent onBTEvent) {

		this.onBTEvent = onBTEvent;
	}

	public interface BTDataMsg {

		public void onDataReceive(float depth, float freq, float smoothFactor);

		public void onKeyStateChanged(int code, int state);
	}

	public JwaooToyBatteryInfo getBatteryInfo() {
		try {
			return mBleToy.getBatteryInfo();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

	JwaooBleToyEventListener jwaooBleToyEventListener = new JwaooBleToyEventListener() {

		@Override
		public boolean onInitialize() {
			// setFreqFuzz(10);
			// setDepthFuzz(50);

			try {
				if (!mBleToy.setLongClickEnable(true))
					return false;
				if (!mBleToy.setMultiClickEnable(true))
					return false;

				btLevel = 0;

				isFilter = false;

				MyLog.d(TAG, "onInitialize...");

				if (mBleToy.getDeviveId() == JwaooBleToy.DEVICE_ID_MODEL06) {
					if (!mBleToy.setMotoEventEnable(true)) {
						return false;
					}

					JwaooToyMotoMode mode = mBleToy.getMotoMode();
					if (mode == null) {
						return false;
					}
					btLevel = mode.getLevel();

				}
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}

			MyLog.e(TAG, "btLevel = " + btLevel);

			isFilter = btLevel != 0;
			smoothSpeed = isFilter ? FilterSpeed : NoFilterSpeed;
			btDataProc = new BTDataProcess();
			mBandDataProc = new BTBandDataProcess();
			onBTState = new BTDataState();
			return true;
		}

		@Override
		public void onBluetoothAdapterStateChanged(boolean enabled) {
			if (enabled) {
				VRApplication.getInstance().tryConnectBT();

			}
		}

		@Override
		public void onConnectFailed() {
			// TODO Auto-generated method stub
			MyLog.d(TAG, "onConnectFailed...");
			// 尝试连接
			if (mBleToy.isPoweredOn())
				VRApplication.getInstance().tryConnectBT();

			if (onBTEvent != null)
				onBTEvent.onConnected(false);

		}

		@Override
		public void onConnectionStateChanged(boolean connected) {
			CavanAndroid.eLog("onConnectionStateChange: connected = "
					+ connected);

			synchronized (BluetoothPlayer.this) {

				if (connected) {

					if (isEventEnable) {

						try {
							mBleToy.setSensorEnable(isEventEnable, SENSOR_DELAY);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}

				if (onBTEvent != null) {

					onBTEvent.onConnected(connected);

				}

			}

		}

		@Override
		public void onMotoStateChanged(int mode, int level) {

			btLevel = level;

			isFilter = btLevel != 0;

			smoothSpeed = isFilter ? FilterSpeed : NoFilterSpeed;

			MyLog.e(TAG, "btLevel = " + btLevel);

		}

		@Override
		public void onSensorDataReceived(JwaooToySensor sensor, byte[] data) {

			// Log.e(TAG,
			// "AccData  "+(float)xAcel+" ,"+(float)yAcel+" ,"+(float)zAcel+","+state);
			// MyLog.e(TAG,"xAcel = "+xAcel + "btData = " + btData[0]);
			if (isEventEnable) {

				double xAcel = -mBleToy.getSensor().getAxisX();
				double yAcel = mBleToy.getSensor().getAxisY();
				double zAcel = mBleToy.getSensor().getAxisZ();
				int state = BTDataState.STATE_BUSY;
				boolean isBand = mBleToy.getDeviveId() == JwaooBleToy.DEVICE_ID_MODEL10;
				if (onBTState != null && isBand) {
					state = onBTState.GetState(xAcel, yAcel, zAcel);
				}

				double[] btData = null;

				if (isBand) {// 手环

					btData = mBandDataProc.getCurDepth(xAcel, isFilter);

				} else {// 飞机杯

					btData = btDataProc.getCurDepth(xAcel, isFilter);
				}

				if (state == BTDataState.STATE_BUSY)// 用本次数据
				{

					btData1 = btData[0];
					btData2 = btData[1];

				} else {// 用上次数据

					btData = new double[] { btData1, btData2 };

				}

				if (onBTDataMsg != null) {

					onBTDataMsg.onDataReceive((float) btData[0],
							(float) btData[1], smoothSpeed);

				}
			}

		}

		@Override
		public void onKeyClicked(int code, int count) {
			MyLog.d(TAG, "onKeyClicked keycode=" + code + " count = " + count);

			if (isEventEnable) {

				if (mBleToy.getDeviveId() == JwaooBleToy.DEVICE_ID_MODEL10) {

					if (count == Constant.BT_ACTION_ONE) {

						code = Constant.BT_KEY_MAX;

					} else if (count == Constant.BT_ACTION_TWO) {

						code = Constant.BT_KEY_O;

						count = Constant.BT_ACTION_ONE;

					} else if (count == Constant.BT_ACTION_THREE) {

						code = Constant.BT_KEY_O;

						count = Constant.BT_ACTION_LONG;
					}

				}

				if (onBTDataMsg != null) {

					onBTDataMsg.onKeyStateChanged(code, count);

				}
			}

		}

		@Override
		public void onKeyLongClicked(int code) {

			MyLog.d(TAG, "onKeyLongClicked keycode=" + code);

			if (isEventEnable) {

				if (mBleToy.getDeviveId() == JwaooBleToy.DEVICE_ID_MODEL10) {

					code = Constant.BT_KEY_MAX;
				}

				if (onBTDataMsg != null) {

					onBTDataMsg
							.onKeyStateChanged(code, Constant.BT_ACTION_LONG);

				}
			}

		}

		@Override
		public void onDebugDataReceived(byte[] arg0) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onKeyStateChanged(int arg0, int arg1) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onUpgradeComplete(boolean arg0) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onBatteryStateChanged(
				JwaooToyBatteryInfo jwaootoybatteryinfo) {
			// TODO Auto-generated method stub
			
		}
	};
}
